package com.suxin.websocket;

import com.suxin.websocket.handler.AbstractHandler;
import com.suxin.websocket.model.BaseModel;
import com.suxin.websocket.session.SessionHolder;
import com.suxin.websocket.session.SessionPath;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.websocket.*;
import java.util.Objects;

/**
 * @author Tang
 * @classname AbstractWebSocketServer
 * @description [  ]
 * @date 2022/3/24 10:07
 */
@Getter
@Setter
@Slf4j
public abstract class AbstractWebSocketServer<T> implements ApplicationContextAware {

    private SessionHolder sessionHolder;

    private AbstractHandler abstractHandler;

    private SessionPath sessionPath;

    protected static ApplicationContext applicationContext;


    @OnOpen
    public void onOpen(Session session) {
        log.info("有客户端进来了:{}",session.getRequestURI());
        getSessionHolder().addSession(session, this.getSessionPath().buildKey(session));
        this.abstractHandler = getAbstractHandler();
        this.sessionHolder = getSessionHolder();
        this.sessionPath = getSessionPath();
    }

    @OnClose
    public void onClose(Session session) {
        String key = this.getSessionPath().getKey();
        log.info("客户端关闭:{}", getSessionHolder().getSession(key).getRequestURI());
        getSessionHolder().removeSession(key);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到客户端的数据为:{}", message);
        if (Objects.isNull(getAbstractHandler())) {
            return;
        }
        BaseModel baseModel = BaseModel.getType(message);
        if (Objects.nonNull(baseModel)) {
            getAbstractHandler().handler(baseModel);
            return;
        }
        log.error("收到客户端的数据为:{}", message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        String key = this.getSessionPath().getKey();
        getSessionHolder().removeSession(key);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        AbstractWebSocketServer.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}